package edu.washington.ling.syntric.io;

import java.util.HashMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Set;
import java.io.*;

public class TreeFileReaderDir extends TreeFileReader {

	private static FileFilter fileOnlyFilter = new FileFilter() {
		public boolean accept(File file) {
			return file.isFile();
		}
	};
	private HashMap<String, File> treeFileMap;
	private Iterator<File> treeFileIterator;
	
	public TreeFileReaderDir(String path, String layer) throws IOException {
		super(path, layer);
		File treeDir = new File(super.getPath());
		if (!treeDir.isDirectory()) {
			String errStr = String.format("The path \'%s\' was not a valid directory", path);
			throw new FileNotFoundException(errStr);
		}
		treeFileMap = new HashMap<String, File>();
		List<File> treeFiles = Arrays.asList(treeDir.listFiles(fileOnlyFilter));
		for(File treeFile: treeFiles) {
			String fileName = treeFile.getName();
			String treeID = fileName.replaceAll("\\.\\w+$", "");
			if (treeFileMap.containsKey(treeID)) {
				String errStr = String.format("Error: sentence \'%s\' has already been seen.\n", treeID);
				System.err.println(errStr);
			}
			else {
				treeFileMap.put(treeID, treeFile);
			}
		}
		treeFileIterator = treeFiles.iterator();
	}
	@Override
	public int numTrees() {
		return treeFileMap.size();
	}
	@Override
	public Set<String> getIDs() {
		return treeFileMap.keySet();
	}
	@Override
	public boolean hasTreeRepWithID(String id) {
		return treeFileMap.containsKey(id);
	}
	@Override
	public TreeRepresentation readNextTreeRep() throws IOException {
		ArrayList<String> lines = new ArrayList<String>();
		TreeRepresentation treeRep = null;
		if (treeFileIterator.hasNext()) {
			File treeFile = treeFileIterator.next();
			BufferedReader br = new BufferedReader(new FileReader(treeFile));
			String line;
			while ((line = br.readLine()) != null) {
				if (line.length() > 0 && !line.startsWith(";")) {
					lines.add(line);
				}
			}
			treeRep = new TreeRepresentation(lines, this.getLayer());
		}
		return treeRep;
	}
	
	@Override
	public TreeRepresentation readTreeRepWithID(String id) throws IOException {
		ArrayList<String> lines = new ArrayList<String>();
		TreeRepresentation treeRep = null;
		if (treeFileMap.containsKey(id)) {
			File treeFile = treeFileMap.get(id);
			BufferedReader br = new BufferedReader(new FileReader(treeFile));
			String line;
			while ((line = br.readLine()) != null) {
				if (line.length() > 0 && !line.startsWith(";")) {
					lines.add(line);
				}
			}
			if (lines.size() > 0) {
				treeRep = new TreeRepresentation(lines, this.getLayer());
			}
		}
		return treeRep;
	}

}
